#include "ButtonHandler.h"

ButtonHandler::ButtonHandler(uint8_t pin, bool pullup) 
    : _pin(pin), _pullup(pullup), _lastState(false), _currentState(false), 
      _lastDebounceTime(0), _pressStartTime(0) {
    if (_pullup) {
        pinMode(_pin, INPUT_PULLUP);
    } else {
        pinMode(_pin, INPUT);
    }
}

void ButtonHandler::update() {
    bool reading = digitalRead(_pin);
    if (_pullup) {
        reading = !reading;
    }

    if (reading != _lastState) {
        _lastDebounceTime = millis();
    }

    if ((millis() - _lastDebounceTime) > debounceDelay) {
        if (reading != _currentState) {
            _currentState = reading;
        }
    }

    _lastState = reading;
}

bool ButtonHandler::wasPressed() {
    update();
    return _currentState;
}

bool ButtonHandler::wasReleased() {
    update();
    static bool last = _currentState;
    bool released = false;
    if (last && !_currentState) {
        released = true;
    }
    last = _currentState;
    return released;
}

bool ButtonHandler::isPressed() {
    update();
    return _currentState;
}

unsigned long ButtonHandler::getPressDuration() {
    if (isPressed()) {
        if (_pressStartTime == 0) {
            _pressStartTime = millis();
        }
        return millis() - _pressStartTime;
    } else {
        _pressStartTime = 0;
        return 0;
    }
}